//
//  BBGlobalSingleton.m
//  BabyThermometer
//
//  Created by CaiLei on 10/2/14.
//  Copyright (c) 2014 baohu. All rights reserved.
//

#import "BBGlobalSingleton.h"
#import "CoreLogFormatter.h"
#import "CoreFileLogger.h"

static NSString * const kUserInfo = @"kUserInfo";
static NSString * const kBabys = @"kBabys";

@implementation BBUserInfo
@end

@implementation BBBabyInfo
@end

@implementation BBGlobalSingleton
+ (BBGlobalSingleton *)sharedInstance {
    NSAssert([BBGlobalSingleton class] == self, @"Incorrect use of singleton : %@, %@", [BBGlobalSingleton class], [self class]);
    static dispatch_once_t once;
    static BBGlobalSingleton *sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

int ddLogLevel = LOG_LEVEL_VERBOSE;
+ (void)setupCore {
    [self setupLogger];
    [self setupCoreData];
}

+ (void)clearCore {
    [MagicalRecord cleanUp];
}

+ (void)setupLogger {
    CoreLogFormatter *formatter = [[CoreLogFormatter alloc] init];

    // 1, add tty logger
    [[DDTTYLogger sharedInstance] setLogFormatter:formatter];
    UIColor *pink = [UIColor colorWithRed:(255 / 255.0) green:(58 / 255.0) blue:(159 / 255.0) alpha:1.0];
    [[DDTTYLogger sharedInstance] setForegroundColor:[UIColor redColor] backgroundColor:nil forFlag:LOG_FLAG_ERROR];
    [[DDTTYLogger sharedInstance] setForegroundColor:[UIColor yellowColor] backgroundColor:nil forFlag:LOG_FLAG_WARN];
    /* [[DDTTYLogger sharedInstance] setForegroundColor:pink backgroundColor:nil forFlag:LOG_FLAG_INFO]; */ // 用默认颜色显示 LOG_FLAG_INFO
    [[DDTTYLogger sharedInstance] setForegroundColor:pink backgroundColor:nil forFlag:LOG_FLAG_VERBOSE];

    // 2, add file logger
    DDLogFileManagerDefault *fm = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:[BBGlobalSingleton appDocumentPath]];
    CoreFileLogger *fl = [[CoreFileLogger alloc] initWithLogFileManager:fm];
    [fl setLogFormatter:formatter];
    
    // 3, setup and verify
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    [DDLog addLogger:fl];
    
    char *xcode_colors = getenv("XcodeColors");
    NSString *xcodecolorsInfo = nil;
    
    if (xcode_colors) {
        if (strcmp(xcode_colors, "YES") == 0) {
            xcodecolorsInfo = @"XcodeColors enabled";
            [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
        }
        else {
            xcodecolorsInfo = @"XcodeColors disabled";
        }
    }
    else {
        xcodecolorsInfo = @"XcodeColors not detected";
    }
    
    DDLogError(@"Error : %@", xcodecolorsInfo);
    DDLogWarn(@"Warn : %@", xcodecolorsInfo);
    DDLogInfo(@"Info : %@", xcodecolorsInfo);
    DDLogVerbose(@"Verbose : %@", xcodecolorsInfo);
}

+ (void)setupCoreData {
    [MagicalRecord setShouldDeleteStoreOnModelMismatch:YES];
    
    NSString *path = [[BBGlobalSingleton appDocumentPath] stringByAppendingPathComponent:@"BBCoreDataDB.sqlite"];
    [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:path];
}

+ (NSString *)appDocumentPath {
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [searchPaths lastObject];
    return documentPath;
}

- (void)saveToDisk {
    NSString *userinfo = [self.currentUser toJSONString];
    [[NSUserDefaults standardUserDefaults] setObject:userinfo forKey:kUserInfo];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)loadFromDisk {
    NSString *userinfo = [[NSUserDefaults standardUserDefaults] objectForKey:kUserInfo];
    self.currentUser = [[BBUserInfo alloc] initWithString:userinfo error:nil];
    if (isEmpty(self.currentUser)) {
        self.currentUser = [[BBUserInfo alloc] init];
    }
}

@end

#pragma mark - c func
BOOL isEmpty(id aItem) {
    return aItem == nil
    || ([aItem isKindOfClass:[NSNull class]])
    || (([aItem respondsToSelector:@selector(length)])
        && ([aItem length] == 0))
    || (([aItem respondsToSelector:@selector(length)])
        && ([aItem length] == 0))
    || (([aItem respondsToSelector:@selector(count)])
        && ([aItem count] == 0));
}
